package com.hatricks.is.controller.download;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import com.alibaba.fastjson.JSON;
import com.hatricks.is.common.exception.BusinessException;
import com.hatricks.is.infrastructure.web.RequestUtils;
import com.hatricks.is.tracelog.MyThreadPoolTaskExecutor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

/**
 * @packageName: com.hatricks.controller.download
 * @className: DownloadController
 * @author: yanyh yanyh@glodon.com
 * @date: 2024/4/2 14:02
 * @description:
 */
@RequestMapping()
@Controller
@Slf4j
public class DownloadController {

    public static final String DOWNLOAD_PREFIX = "GENERAL_DOWNLOAD_DISK";

    @PostMapping("download")
    @ResponseBody
    public void downloadStream(@RequestBody DownloadParam param) throws IOException {
        File file = getAbsoluteFile(param);
        // 设置响应头部
        HttpServletResponse response = RequestUtils.getHttpServletResponse();
        response.setContentType(Files.probeContentType(file.toPath()));
        response.setHeader(Header.CONTENT_DISPOSITION.toString(), "attachment; filename=\"" + Base64.encode(file.getName()) + "\"");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        // 读取文件并将其发送到客户端
        try (OutputStream out = response.getOutputStream();
             FileInputStream in = IoUtil.toStream(file)) {
            IoUtil.copy(in, out);
        }
    }

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Resource(name = "BaseExecutor")
    private MyThreadPoolTaskExecutor threadPoolTaskExecutor;

    @GetMapping("/download/index")
    public String downloadJump(Model model) {
        log.info("当前下载的对象数据为:[{}]", JSON.toJSONString(model));
        log.info("测试1111");
        threadPoolTaskExecutor.execute(() -> {
            log.info("异步链路追踪");
        });
        model.addAttribute("message", "Hello, Thymeleaf!");
        return "download"; // 返回hello.html模板
    }

    private static File getAbsoluteFile(DownloadParam param) {
        String filePath = param.getFilePath();
        if (StrUtil.isEmpty(filePath)) {
            throw new BusinessException("下载路径不能为空");
        }
        return FileUtil.file(filePath);
    }

    @Data
    public static class DownloadParam {
        private String filePath;
    }
}
